﻿using System;
using System.Collections;
using System.Threading;
using Microsoft.SPOT;
using Microsoft.SPOT.Presentation;
using Microsoft.SPOT.Presentation.Controls;
using Microsoft.SPOT.Presentation.Media;
using Microsoft.SPOT.Touch;

using Gadgeteer.Networking;
using GT = Gadgeteer;
using GTM = Gadgeteer.Modules;
using Gadgeteer.Modules.GHIElectronics;
using Gadgeteer.Modules.Community.XBee;
using System.IO;
using Gadgeteer.Modules.Seeed;
using Gadgeteer.Modules.Community;

namespace Gadgeteer.Cookbook.BuildABear
{
    public partial class Program
    {
        GT.StorageDevice storage;
        NodeDescription peerNode;
        EmotionMachine emotionMachine;
        Timer reflectiveTimer;

        void ProgramStarted()
        {
            Debug.Print("Program Started");

            emotionMachine = new EmotionMachine() { DominantState = Emotions.Hunger };

            camera.PictureCaptured += new Camera.PictureCapturedEventHandler(camera_PictureCaptured);

            sdCard.MountSDCard();
            storage = sdCard.GetStorageDevice();

            music.DebugPrintEnabled = true;

            xBeeClient.StringReceived += new StringReceivedEventHandler(xBeeClient_StringReceived);
            xBeeClient.DiscoverNodesCompleted += new DiscoverNodesCompletedEventHandler(xBeeClient_DiscoverNodesCompleted);

            xBeeClient.DiscoverNodesAsync();

            accelerometer.MeasurementRange = Accelerometer.Range.TwoG;
            accelerometer.Calibrate();
            accelerometer.ContinuousMeasurementInterval = new TimeSpan(0, 0, 0, 0, 500);
            accelerometer.MeasurementComplete += new Accelerometer.MeasurementCompleteEventHandler(accelerometer_MeasurementComplete);
            accelerometer.EnableThresholdDetection(3.0, true, true, true, true, false, false);
            accelerometer.ThresholdExceeded += new Accelerometer.ThresholdExceededEventHandler(accelerometer_ThresholdExceeded);

            reflectiveTimer = new Timer(30000);
            reflectiveTimer.Tick += new Timer.TickEventHandler(reflectiveTimer_Tick);
            reflectiveTimer.Start();
        }

        void accelerometer_ThresholdExceeded(Accelerometer sender)
        {
            Debug.Print("Accelerometer ThresholdExceeded, triggering fear: ");
            emotionMachine.DominantState = Emotions.Fear;
            Roar();
            sender.ResetThresholdDetection();
        }

        void reflectiveTimer_Tick(Timer timer)
        {
            switch (emotionMachine.DominantState)
            {
                case Emotions.Fear:
                    Roar();
                    break;
                case Emotions.Hunger:
                    Hunger();
                    break;

            }
        }

        void xBeeClient_DiscoverNodesCompleted(object sender, DiscoverNodesCompletedEventArgs e)
        {
            this.peerNode = e.Result.NodeDescription;
        }

        void camera_PictureCaptured(Camera sender, Picture picture)
        {
            if (null != this.peerNode)
            {
                xBeeClient.UploadPictureAsync(this.peerNode, picture.PictureData);
            }
        }

        void accelerometer_MeasurementComplete(Accelerometer sender, Accelerometer.Acceleration acceleration)
        {
            Debug.Print(acceleration.ToString());
        }

        void xBeeClient_StringReceived(object sender, StringReceivedEventArgs e)
        {
            // TODO: come up with a better messaging system!
            // don't even waste any time validating, just blow chunks
            string message = e.Message.ToLower().Trim();
            string[] messageParts = message.Split(' ');
            string command = messageParts[0];

            switch (command)
            {
                case "roar":
                    Roar();
                    break;
                case "bearcam":
                    BearCam();
                    break;
                case "emotion":
                    switch (messageParts[1])
                    {
                        case "hungry":
                            emotionMachine.DominantState = Emotions.Hunger;
                            break;
                        case "fear":
                            emotionMachine.DominantState = Emotions.Fear;
                            break;
                    }
                    break;
            }
 
        }

        private void BearCam()
        {
            camera.TakePicture();
        }

        private void Hunger()
        {
            PlaySound("\\hungry.mp3");
        }

        private void Roar()
        {
            PlaySound("\\lion_roar.mp3");
        }

        private void PlaySound(string fileName)
        {
            using (FileStream fs = storage.Open(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read))
            {
                music.SetVolume(200);
                music.Play(fs);
                // have to wait till music player is done so we can release the file stream
                while (music.IsBusy)
                {
                    Thread.Sleep(10);
                }
            }
        }

      
    }
}
